﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using NHibernate;

namespace WirtualneNauczanie.Web
{
    public partial class CourseTest : System.Web.UI.Page
    {
        String yourcourseid, section;
        DropDownList[] questionsList;
        int numOfRows;

        protected void Page_Load(object sender, EventArgs e)
        {
            yourcourseid = Request.QueryString["yourcourseid"];
            section = Request.QueryString["section"];

            /*SqlDataSource1.SelectCommand = "SELECT SectionQuestionID, QuestionText FROM SectionQuestions WHERE (CourseSectionID = " + section + ")";
            DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
            numOfRows = dv.Table.Rows.Count;
            
            Label[] questionLabel = new Label[numOfRows];
            questionsList = new DropDownList[numOfRows];
            HtmlContainerControl[] para = new HtmlContainerControl[numOfRows*2]; //= new HtmlGenericControl("p");


            for (int i = 0; i < numOfRows; i++)
            {

                int sectionQuestionId = (int)dv.Table.Rows[i][0];
                String questionText = (String)dv.Table.Rows[i][1];

                SqlDataSource1.SelectCommand = "SELECT AnswerText, QuestionAnswerID FROM QuestionAnswers WHERE (SectionQuestionID = " + sectionQuestionId + ")";
                //DataView dv2 = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
                //String questionOneOfAnswers = (String)dv2.Table.Rows[0][0];
                //String answerId = (String)dv2.Table.Rows[0][1];*/

            /*DropDownList1.DataSource = SqlDataSource1;
            DropDownList1.DataTextField = "AnswerText";
            DropDownList1.DataValueField = "QuestionAnswerID";
            DropDownList1.DataBind();*/

            //Dodanie pytania i odpowiedzi do pytania
            /*para[i] = new HtmlGenericControl("p");
            PlaceHolder1.Controls.Add(para[i]);
            questionLabel[i] = new Label();
            questionLabel[i].Text = questionText;
            PlaceHolder1.Controls.Add(questionLabel[i]);

            para[i*2] = new HtmlGenericControl("p");
            PlaceHolder1.Controls.Add(para[i*2]);
            questionsList[i] = new DropDownList();
            questionsList[i].DataSource = SqlDataSource1;
            questionsList[i].DataTextField = "AnswerText";
            questionsList[i].DataValueField = "QuestionAnswerID";
            questionsList[i].DataBind();
            PlaceHolder1.Controls.Add(questionsList[i]);*/
            kw8();

        }


        protected void Button1_Click(object sender, EventArgs e)
        {
            kw9();
            //Sprawdzenie testu

            //Sprawzenie ile odpowiedzi jest poprawnych
            /*SqlDataSource1.SelectCommand = "SELECT CorrectAnswer FROM SectionQuestions WHERE (CourseSectionID = " + section + ")";
            DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

            int goodAnswersCount = 0;
            for (int i = 0; i < numOfRows; i++)
            {
                int goodAnswerId = (int)dv.Table.Rows[i][0];

                if (goodAnswerId == Int32.Parse(questionsList[i].SelectedValue))
                {
                    goodAnswersCount = goodAnswersCount +1;
                }

            }
            //Pobranie daty podjęcia testu
            DateTime testTakenDate = System.DateTime.Today;

            //Pobranie ID usera
            MembershipUser myObject = Membership.GetUser();
            string StudentID = myObject.ProviderUserKey.ToString();


            //Popranie maksymalnego id z bazy wynikow

            int QuizResultID  = 0;
            SqlDataSource1.SelectCommand = "SELECT MAX(QuizResultID) FROM QuizResults";
            DataView dv2 = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

            if (dv2.Table.Rows[0][0].Equals(System.DBNull.Value))
            {
                QuizResultID = 1;
            }
            else
            {
                QuizResultID = (int)dv2.Table.Rows[0][0];
            }


            //Dodanie wyników testu do bazy danych SQL
            SqlDataSource1.InsertCommand = "INSERT INTO QuizResults (QuizResultID, CourseSectionID, Score, TotalQuestions, DateTaken, StudentID) VALUES " +
            " ('" + (QuizResultID + 1) + "','" + section + "','" + goodAnswersCount + "','" + numOfRows + "','" + testTakenDate + "','" + StudentID + "')";
            SqlDataSource1.Insert();*/
            //Label1.Text = "" + goodAnswersCount;

            //Przekierowanie na stronę główną kursu
            Response.Redirect("Course.aspx?yourcourseid=" + yourcourseid);
        }

        //Wyswietlenie pytan na ekranie (CourseTest.aspx)
        private void kw8()
        {

            int section = 1;

            ISession session = NHibernateHelper.GetCurrentSession();
            ITransaction tx = session.BeginTransaction();

            string querystring = "select sq.Sectionquestionid, sq.Questiontext from Sectionquestions sq where sq.Coursesectionid = " + section;
            IQuery query = session.CreateQuery(querystring);

            numOfRows = 0;

            foreach (Object[] elements in query.Enumerable())
            {
                numOfRows++;
            }

            Label[] questionLabel = new Label[numOfRows];
            questionsList = new DropDownList[numOfRows];
            HtmlContainerControl[] para = new HtmlContainerControl[numOfRows * 2];

            int i = 0;
            foreach (Object[] elements in query.Enumerable())
            {
                string querystring2 = "select qa.Questionanswerid, qa.Answertext from Questionanswers qa where qa.Sectionquestionid = " + elements[0].ToString();
                IQuery query2 = session.CreateQuery(querystring2);

                para[i] = new HtmlGenericControl("p");
                PlaceHolder1.Controls.Add(para[i]);
                questionLabel[i] = new Label();
                questionLabel[i].Text = elements[1].ToString();
                PlaceHolder1.Controls.Add(questionLabel[i]);

                para[i * 2] = new HtmlGenericControl("p");
                PlaceHolder1.Controls.Add(para[i * 2]);
                questionsList[i] = new DropDownList();
                foreach (Object[] elements2 in query2.Enumerable())
                {
                    questionsList[i].Items.Add(new ListItem(elements2[1].ToString(), elements2[0].ToString()));
                }

                PlaceHolder1.Controls.Add(questionsList[i]);

                i++;
            }



            //tx.Commit();
            NHibernateHelper.CloseSession();
        }

      /*  private void kw8()
        {
            DataClasses1DataContext db = new DataClasses1DataContext();

            var query1 = from sq in db.SectionQuestions
                         where sq.CourseSectionID.Equals(section)
                         select new
                         {
                             id = sq.SectionQuestionID,
                             text = sq.QuestionText
                         };
            numOfRows = 0;

            foreach (var iter in query1)
            {
                numOfRows++;
            }

            Label[] questionLabel = new Label[numOfRows];
            questionsList = new DropDownList[numOfRows];
            HtmlContainerControl[] para = new HtmlContainerControl[numOfRows * 2];


            int i = 0;
            foreach (var sq in query1)
            {

                var query2 = from qa in db.QuestionAnswers
                             where qa.SectionQuestionID.Equals(sq.id)
                             select new
                             {
                                 id = qa.QuestionAnswerID,
                                 text = qa.AnswerText
                             };


                para[i] = new HtmlGenericControl("p");
                PlaceHolder1.Controls.Add(para[i]);
                questionLabel[i] = new Label();
                questionLabel[i].Text = sq.text;
                PlaceHolder1.Controls.Add(questionLabel[i]);

                para[i * 2] = new HtmlGenericControl("p");
                PlaceHolder1.Controls.Add(para[i * 2]);
                questionsList[i] = new DropDownList();
                foreach (var answers in query2)
                {
                    questionsList[i].Items.Add(new ListItem(answers.text, Convert.ToString(answers.id)));
                }

                PlaceHolder1.Controls.Add(questionsList[i]);

                i++;
            }
        }//koniec kw8
        */


        //Po nacisnieciu przycisku sprawdzane są odpowiedzi i wypełniane odpowiednie tabele
        private void kw9()
        {
            MembershipUser myObject = Membership.GetUser();
            Guid sid = new Guid(myObject.ProviderUserKey.ToString());

            int section = 1;
            ISession session = NHibernateHelper.GetCurrentSession();
            ITransaction tx = session.BeginTransaction();

            string querystring = "select sq.Correctanswer from Sectionquestions sq where sq.Coursesectionid = " + section;
            IQuery query1 = session.CreateQuery(querystring);

            int i = 0;
            int goodAnswersCount = 0;
            foreach (int goodanswer in query1.Enumerable())
            {
                if (goodanswer == Int32.Parse(questionsList[i].SelectedValue))
                {
                    goodAnswersCount = goodAnswersCount + 1;
                }
                i++;
            }

            //Pobranie daty podjęcia testu
            DateTime testTakenDate = System.DateTime.Today;

            //Pobranie ID usera
            //MembershipUser myObject = Membership.GetUser();
            //string sid = myObject.ProviderUserKey.ToString();
            

            Quizresults quizresults = new Quizresults();
            quizresults.Datetaken = testTakenDate;
            quizresults.Studentid = sid;
            quizresults.Score = goodAnswersCount;
            quizresults.Totalquestions = numOfRows;
            quizresults.Coursesectionid = section;

            session.Save(quizresults);
            tx.Commit();
            NHibernateHelper.CloseSession();

        }


       /* private void kw9()
        {
            //int section = 1;
            //"SELECT CorrectAnswer FROM SectionQuestions WHERE (CourseSectionID = " + section + ")";
            DataClasses1DataContext db = new DataClasses1DataContext();
            var query1 = from sq in db.SectionQuestions
                         where sq.CourseSectionID.Equals(section)
                         select new
                         {
                             correctanswer = sq.CorrectAnswer
                         };
            int i = 0;
            int goodAnswersCount = 0;
            foreach (var q in query1)
            {
                if (q.correctanswer.Equals(Int32.Parse(questionsList[i].SelectedValue)))
                {
                    goodAnswersCount = goodAnswersCount + 1;
                }
                i++;
            }

            int QuizResultID = db.QuizResults.Max(qr => qr.QuizResultID);
            // if (QuizResultID < 0) QuizResultID = 0;

            //Pobranie daty podjęcia testu
            DateTime testTakenDate = System.DateTime.Today;

            //Pobranie ID usera
            MembershipUser myObject = Membership.GetUser();
            string sid = myObject.ProviderUserKey.ToString();


            QuizResult qres = new QuizResult
            {
                QuizResultID = QuizResultID + 1,
                CourseSectionID = Convert.ToInt32(section),
                Score = goodAnswersCount,
                TotalQuestions = numOfRows,
                DateTaken = testTakenDate,
                StudentID = new Guid(sid)

            };
            db.QuizResults.InsertOnSubmit(qres);
            db.SubmitChanges();

        }*/
    }

}

